//
//  ViewController.m
//  21_Network
//
//  Created by 徐昊 on 16/8/11.
//  Copyright © 2016年 徐昊. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) IBOutlet UIImageView *networkImage;

@end

@implementation ViewController
#pragma mark - 同步
- (IBAction)syncConnect:(id)sender {
    NSURL *imageURL = [NSURL URLWithString:@"http://www.lingyu.me/wp-content/uploads/2016/08/www.lingyu.me_20160808081654350.jpg"];
    NSMutableURLRequest *imageURLRequest = [NSMutableURLRequest requestWithURL:imageURL];
    imageURLRequest.HTTPMethod = @"GET";
    NSURLResponse *response = nil;
    NSError *error = nil;
    // 同步请求
    // 参数1: 请求Request
    // 参数2: response
    // 参数3: error指针的地址
    NSData *data = [NSURLConnection sendSynchronousRequest:imageURLRequest returningResponse:&response error:&error];
    if (data) {
        _networkImage.image = [UIImage imageWithData:data];
    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"点击");
}
#pragma mark - 异步
- (IBAction)asyncConnect:(id)sender {
    NSURL *imageURL = [NSURL URLWithString:@"http://www.lingyu.me/wp-content/uploads/2016/08/www.lingyu.me_20160808081654350.jpg"];
    NSMutableURLRequest *imageURLRequest = [NSMutableURLRequest requestWithURL:imageURL];
    imageURLRequest.HTTPMethod = @"GET";
    [NSURLConnection sendAsynchronousRequest:imageURLRequest queue:[NSOperationQueue new] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        _networkImage.image = [UIImage imageWithData:data];
    }];
}
- (IBAction)urlSeesionAsync:(id)sender {
    
    NSURLSession *urlSession = [NSURLSession sharedSession];
    NSURL *imageURL = [NSURL URLWithString:@"http://www.lingyu.me/wp-content/uploads/2016/08/www.lingyu.me_20160808081654350.jpg"];
    NSMutableURLRequest *imageURLRequest = [NSMutableURLRequest requestWithURL:imageURL];
    imageURLRequest.HTTPMethod = @"GET";
    // URLSession 网络请求
    // 参数1: request
    // 参数2: Block, CallBack回调
    // 注意: Session的回调中处于异步线程, 需要返回主线程刷新UI(图片赋值, tableView CollectionView的刷新)
    NSURLSessionDataTask *dataTask = [urlSession dataTaskWithRequest:imageURLRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // 主线程执行图片加载
            _networkImage.image = [UIImage imageWithData:data];
            
        });
    }];
    // 让 dataTask 执行
    [dataTask resume];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
